import copyToClipboard from 'copy-to-clipboard';

import {
  SERVICE_TEL,
  SERVICE_TEL_ESCORT,
} from '../constants/setting';

export function callService(type = 'youyu') {
  switch (type) {
    case 'escort':
      window.location.href = `tel:${SERVICE_TEL_ESCORT.replace(/\s/g, '')}`;
      break;
    default:
      window.location.href = `tel:${SERVICE_TEL.replace(/\s/g, '')}`;
      break;
  }
}

export function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

export function debounced(fn, time = 800) {
  let timerId;
  return function (...args) {
    if (timerId) {
      clearTimeout(timerId);
    }
    timerId = setTimeout(() => {
      fn(...args);
      timerId = null;
    }, time);
  };
}

export function throttled(fn, time) {
  let lastCall = 0;
  return function (...args) {
    const now = (new Date()).getTime();
    if (now - lastCall < time) {
      return;
    }
    lastCall = now;
    return fn(...args);
  };
}

export function hideMobile(mobile = '') {
  return `${mobile.substring(0, 3)}****${mobile.substring(7, 11)}`;
}

export function numberFromString(text = '') {
  let result;
  if (text.replace) {
    result = text.replace(/[^0-9.]/g, ''); // 去掉非数字
  }
  console.log(text, result);

  return Number(result) || 0;
}

export function safeMinus(num1, num2) {
  return (parseInt(num1 * 10000, 10) - parseInt(num2 * 10000, 10)) / 10000;
}

export function safeMulti(num1, num2) {
  return (parseInt(num1 * 10000, 10) * parseInt(num2 * 10000, 10)) / 100000000;
}

export function isFunction(functionToCheck) {
  return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}

export function numberBettween({ max, min, value }) {
  return Math.min(Math.max(min, value), max);
}

export function getBrowserType() {
  const u = navigator.userAgent;
  return {
    trident: u.indexOf('Trident') > -1, // IE内核
    presto: u.indexOf('Presto') > -1, // opera内核
    webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
    android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, // android终端
    iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
    iPad: u.indexOf('iPad') > -1, // 是否iPad
    webApp: u.indexOf('Safari') === -1, // 是否web应该程序，没有头部与底部
    weixin: u.indexOf('MicroMessenger') > -1, // 是否微信 （2015-01-22新增）
    qq: u.match(/\sQQ/i) === ' qq', // 是否QQ
    hcz: u.indexOf('hcz') > -1, // 是否平安好车主
  };
}


export function copy(value, cb) {
  console.log('copy', value);
  if (copyToClipboard(value)) {
    cb();
  }
  // const input = document.createElement('input');
  // document.body.appendChild(input);
  // input.setAttribute('value', value);
  // if (getBrowserType().ios) {
  //   input.contentEditable = true;
  //   input.readOnly = false;
  //   const range = document.createRange();
  //   range.selectNodeContents(input);
  //   const sel = window.getSelection();
  //   sel.removeAllRanges();
  //   sel.addRange(range);
  //   input.setSelectionRange(0, 999999);
  // } else {
  //   input.select();
  // }

  // if (document.execCommand('copy')) {
  //   document.execCommand('copy');
  //   if (cb) {
  //     cb();
  //   }
  // }
  // document.body.removeChild(input);
}


export function closeWindow() {
  window.location.href = 'about:blank';
  window.close();
}

export function chunk(arr, size) {
  let index = 0;
  const newArr = [];
  while (index < arr.length) {
    newArr.push(arr.slice(index, index += size));
  }
  return newArr;
}


export function loadScript(url, callback) {
  const script = document.createElement('script');
  script.type = 'text/javascript';
  if (script.readyState) { //IE
    script.onreadystatechange = () => {
      if (script.readyState === 'loaded' || script.readyState === 'complete') {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else { //Others
    script.onload = () => {
      callback();
    };
  }
  script.src = url;
  document.getElementsByTagName('head')[0].appendChild(script);
}
